/**
 * @Desciption 单表编辑服务JS-tableEditService.jsp
 * @Author guoyanfei
 * @Date 2018/1/3
 */
//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";
var tableEditService = tableEditService || {};

var validationArray = [];
var validationDict = {};

tableEditService.prototype = {
    init: function () { //初始化
        tableEditService.prototype.goblack();
        tableEditService.prototype.bindDbkeyList();
        $("#dbKey").on("change", tableEditService.prototype.bindcfgTableList);
        tableEditService.prototype.editInfo();
        tableEditService.prototype.eventSaveData();
        tableEditService.prototype.eventTabValidationColumn();
        tableEditService.prototype.bingFieldList();
        tableEditService.prototype.openFieldModul();
        tableEditService.prototype.openFieldModulWhenUpdate();
        $("#btn_fieldAdd").on("click", tableEditService.prototype.eventSaveField);
        $("#btn_fieldUpdate").on("click", tableEditService.prototype.eventUpdateFieldList);

        tableEditService.prototype.closeFieldModul();
        tableEditService.prototype.eventDelBaseEditconfig();
        $("#dtConfigId").select2();
        $("#guid").val(GetQueryString("projectid") + "_" + "tableEdit_" + randomWord(false, 4, 4));
        findAllValidationRule();

        function randomWord(randomFlag, min, max) {
            var str = "",
                range = min,
                arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

            // 随机产生
            if (randomFlag) {
                range = Math.round(Math.random() * (max - min)) + min;
            }
            for (var i = 0; i < range; i++) {
                pos = Math.round(Math.random() * (arr.length - 1));
                str += arr[pos];
            }
            return str;
        }
    },
    goblack: function () { //返回服务列表
        $("#btn_back").click(function () {
            var serverType = $("#hid_servertype").val();
            var projectId = $("#hid_projectid").val();
            var seachTxt = (GetQueryStringSeachTxt("seachTxt"));
            window.location.href = postPath + "/prjService/index?order=asc&pageNo=1&pageSize=10&seachTxt=" + seachTxt + "&pcode=" + projectId + '&servertype=' + serverType;
            //retrunIndex();
        });
    },
    bindDbkeyList: function () { //绑定数据源标识下拉列表
        $("#dbKey").html("");
        $.ajax({
            // url: postPath + "/system/tableEdit/getAllcfgDb",
            url: postPath + '/system/sysProject/getProjectToDataSource?pcode=' + GetQueryString("projectid"),
            type: "post",
            async: false,
            success: function (res) {
                $("#dbKey").append('');
                var strtxt = "<option value=''>请选择</option>";
                if (res.success) {
                    $.each(res.data, function (i, e) {
                        strtxt += "<option value='" + e.dbKey + "'>" + e.dbMark + "(" + e.dbKey + ")" + "</option>";
                    });
                }
                $("#dbKey").html(strtxt);
            }, error: function () {
                bootbox.alert("绑定数据源标识失败!");
            }
        });
    },
    bindcfgTableList: function () {//绑定数据表
        $("#dtConfigId").select2("val", "");
        $("#dtConfigId").html("");
        $.ajax({
            url: postPath + "/system/tableEdit/getCfgTableList",
            type: "post",
            data: {dbkey: $("#dbKey").val()},
            async: false,
            success: function (data) {
                $.each(data, function (i, e) {
                    var tableName = e.dtNameCn;
                    // important tip: console.log("'' is false")
                    if(!tableName){
                        console.log("tableName is empty")
                        tableName = e.dtName
                    }
                    $("#dtConfigId").append("<option value=" + e.dtConfigId + ">" + tableName + "</option>");
                });
            }, error: function () {
                bootbox.alert("绑定数据表失败!");
            }
        });
    },
    eventSaveData: function () {//保存服务信息配置
        $("#btn_save").click(function () {
            var validateResult = tableEditService.prototype.validationData();
            if (validateResult) {
                var temp = {
                    guid: $("#guid").val(),
                    servicename: $("#servicename").val(),
                    dbKey: $("#dbKey").val(),
                    dtConfigId: $("#dtConfigId").val(),
                    remark: $("#remark").val(),
                    pcode: $("#hid_projectid").val(),
                    servicetype: $("#hid_servertype").val()
                };
                var editUrl = "";
                if ($("#hid_serviceId").val() == "") {
                    //新增
                    editUrl = postPath + "/system/tableEdit/addCfgEdit";
                } else {
                    //修改
                    editUrl = postPath + "/system/tableEdit/updateCfgEdit";
                }
                $.ajax({
                    url: editUrl,
                    type: "post",
                    data: JSON.stringify(temp),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        if (res > 0) {
                            $("#hid_serviceId").val($("#guid").val());
                            bootbox.alert("保存成功!");
                        } else {
                            bootbox.alert("保存失败,请刷新后重试!");
                        }
                    }, error: function () {
                        bootbox.alert("保存失败,请刷新后重试!");
                    }
                });
            }
        });

    },
    validationData: function () {//验证数据
        if ($("#dbKey").val() == "") {
            $("#errorMessage").html("数据库标识不能为空!");
            return false;
        } else {
            $("#errorMessage").html("");
        }

        if ($("#guid").val() == "") {
            $("#errorMessage").html("服务ID不能为空，且唯一!");
            return false;
        } else {
            if ($("#hid_serviceId").val() == "") {
                //新增操作需验证服务ID不能重复
                var isExit = false;
                $.ajax({
                    url: postPath + "/system/tableEdit/isExitInfoByguid",
                    type: "post",
                    data: {guid: $("#guid").val()},
                    async: false,
                    success: function (data) {
                        isExit = data;
                    }
                });

                if (isExit) {
                    $("#errorMessage").html("服务ID已存在，请重新输入!");
                    return false;
                } else {
                    $("#errorMessage").html("");
                }
            } else {
                $("#errorMessage").html("");
            }
        }

        if ($("#servicename").val() == "") {
            $("#errorMessage").html("服务名称不能为空!");
            return false;
        } else {
            $("#errorMessage").html("");
        }

        if ($("#dtConfigId").val() == "") {
            $("#errorMessage").html("表名称不能为空!");
            return false;
        } else {
            $("#errorMessage").html("");
        }

        return true;
    },
    goTabBlack: function () {//跳转Tab服务信息配置
        $('#myTab a[href="#tab_1_1_1"]').tab('show');
    },
    eventTabValidationColumn: function () {//列校验规则配置选择
        $("#a_tab_d").click(function () {
            if ($("#hid_serviceId").val() == "") {
                bootbox.alert("请先设置服务信息配置!");
                setTimeout(tableEditService.prototype.goTabBlack, 200);
                return;
            }
            $("#tb_fieldList").bootstrapTable('refresh');
            tableEditService.prototype.getBaseEditConfigList();
        });
    },
    editInfo: function () {//修改服务初始化
        if ($("#hid_operate").val() == "edit") {
            $.ajax({
                url: postPath + "/system/tableEdit/selectCfgEidtByguid",
                type: "post",
                data: {guid: $("#hid_serviceId").val()},
                success: function (data) {
                    if (data != null) {
                        $("#dbKey").val(data.dbKey);
                        $("#guid").val(data.guid);
                        $("#servicename").val(data.servicename);
                        tableEditService.prototype.bindcfgTableList();
                        $("#dtConfigId").val(data.dtConfigId).trigger("change");
                        $("#remark").val(data.remark);
                        $("#guid").attr("readOnly", "true");
                    }
                }
            });
        }
    },
    bingFieldList: function () {//绑定字段列表模态框
        //加载数据
        $("#tb_fieldList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/tableEdit/getFieldListByguid',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            queryParams: {guid: $("#hid_serviceId").val()},
            uniqueId: "key", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段名称',
                field: 'dfName',
                align: 'center',
                valign: 'middle',
                width: '200px'
            }, {
                title: '字段中文名称',
                field: 'dfNameCn',
                align: 'center',
                valign: 'middle',
                width: '200px'
            }, {
                title: '字段类型',
                field: 'dtType',
                align: 'center',
                valign: 'middle',
                width: '100px'
            }, {
                title: '验证规则',
                field: 'validatecode',
                align: 'center',
                valign: 'middle',
                width: '150px',
                editable: {
                    type: 'select',
                    title: '验证规则',
                    source: validationArray
                }
            }, {
                title: '是否条件字段',
                field: 'iscondition',
                align: 'center',
                valign: 'middle',
                width: '100px',
                editable: {
                    type: 'select',
                    title: '是否条件字段',
                    source:[
                        {value: '0', text: '否'},
                        {value: '1', text: '是'}
                    ]
                }
            }, {
                title: '字段显示顺序',
                field: 'ordersort',
                align: 'center',
                valign: 'middle',
                width: '100px',
                visible: false,
                editable: {
                    type: 'text',
                    title: '字段显示顺序'
                }

            }, {
                title: '字段显示类型',
                field: 'showtype',
                align: 'center',
                valign: 'middle',
                width: '100px',
                sortable: false,
                editable: {
                    type: 'select',
                    title: '字段显示类型',
                    source:[
                        {value: '0', text: '文本框'},
                        {value: '1', text: '下拉列表'},
                        {value: '2', text: '单选按钮'}
                    ]
                }
            }]
        });
    },

    bingFieldListBySelectUpdate: function (dataList) {
        $("#tb_fieldList").bootstrapTable('destroy').bootstrapTable({
            data: dataList,
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            queryParams: {guid: $("#hid_serviceId").val()},
            uniqueId: "key", // 每一行的唯一标识
            columns: [{
                title: '字段名称',
                field: 'dfname',
                align: 'center',
                valign: 'middle',
                width: '200px'
            }, {
                title: '字段中文名称',
                field: 'dfnameCn',
                align: 'center',
                valign: 'middle',
                width: '200px'
            }, {
                title: '字段类型',
                field: 'fieldType',
                align: 'center',
                valign: 'middle',
                width: '100px'
            }, {
                title: '验证规则',
                field: 'validatecode',
                align: 'center',
                valign: 'middle',
                width: '150px',
                editable: {
                    type: 'select',
                    title: '验证规则',
                    source: validationArray
                }
            }, {
                title: '是否条件字段',
                field: 'iscondition',
                align: 'center',
                valign: 'middle',
                width: '100px',
                editable: {
                    type: 'select',
                    title: '是否条件字段',
                    source:[
                        {value: '0', text: '否'},
                        {value: '1', text: '是'}
                    ]
                }
            }, {
                title: '字段显示顺序',
                field: 'ordersort',
                align: 'center',
                valign: 'middle',
                width: '100px',
                visible: false,
                editable: {
                    type: 'text',
                    title: '字段显示顺序'
                }

            }, {
                title: '字段显示类型',
                field: 'showtype',
                align: 'center',
                valign: 'middle',
                width: '100px',
                sortable: false,
                editable: {
                    type: 'select',
                    title: '字段显示类型',
                    source:[
                        {value: '0', text: '文本框'},
                        {value: '1', text: '下拉列表'},
                        {value: '2', text: '单选按钮'}
                    ]
                }
            }]
        });
    },

    eventSaveField: function () {//保存勾选的列
        var rowList = $('#tb_fieldList').bootstrapTable('getSelections');
        if (rowList == null || rowList == "") {
            bootbox.alert("请最少选择一行!");
            return;
        }


        // here assemble baseEditconfig
        var baseEditConfigList = [];
        console.log("luowen rowList", rowList);
        rowList.forEach( row => {
            var baseEditConfig = {
                serviceid : $("#hid_serviceId").val(),
                fieldid: row.guid,
                validatecode: row.validatename,
                iscondition: row.iscondition,
                ordersort: row.ordersort,
                showtype: row.showtype
            }
            baseEditConfigList.push(baseEditConfig);
        });

        console.log("luowen baseEditConfigList", baseEditConfigList);

        $.ajax({
            url: postPath + "/system/tableEdit/batchAddBaseEditconfigList?serviceId=" + $("#hid_serviceId").val(),
            type: "post",
            contentType: "application/json",

           data: JSON.stringify(baseEditConfigList),
            success: function (data) {
                if (data > 0) {
                    $("#tb_fieldList").bootstrapTable('refresh');
                    $("#FieldModul").modal('hide');
                } else {
                    bootbox.alert("保存失败，请刷新后重试!");
                }
            }
        });
    },

    eventUpdateFieldList: function () {//
        var rowList = $('#tb_fieldList').bootstrapTable('getData');
        var baseEditConfigList = rowList;
        console.log("luowen update baseEditConfigList", baseEditConfigList);

        $.ajax({
            url: postPath + "/system/tableEdit/batchUpdateBaseEditconfigList?serviceId=" + $("#hid_serviceId").val(),
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(baseEditConfigList),
            success: function (data) {
                if (data > 0) {
                    $("#tb_fieldList").bootstrapTable('refresh');
                    $("#FieldModul").modal('hide');
                } else {
                    bootbox.alert("保存失败，请刷新后重试!");
                }
            }
        });
    },
    openFieldModul: function () {
        $("#btn_columnAdd").click(function () {

            setOperateMethod("add")

            tableEditService.prototype.bingFieldList();
            $("#FieldModul").modal('show');
        });
    },
    openFieldModulWhenUpdate: function(){
        $("#btn_columnUpdate").click(function () {

            setOperateMethod("update")

            var rowList = $("#tb_columnfieldList").bootstrapTable("getSelections");
            if(rowList == null)
                return;

            console.log("luowen update rowList is ", rowList);
            tableEditService.prototype.bingFieldListBySelectUpdate(rowList);
            $("#FieldModul").modal('show');
        });

    },
    closeFieldModul: function () {
        $("#FieldModul").live('hidden.bs.modal', function (e) {
            $("#tb_fieldList").bootstrapTable('refresh');
            tableEditService.prototype.getBaseEditConfigList();
        });
    },
    getBaseEditConfigList: function () {//编辑信息配置显示列表
        //加载数据
        $("#tb_columnfieldList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/tableEdit/getAllBaseEditByServiceId',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            queryParams: {serviceId: $("#hid_serviceId").val()},
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段名称',
                field: 'dfname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段中文名称',
                field: 'dfnameCn',
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段类型',
                field: 'fieldType',
                align: 'center',
                valign: 'middle'
            }, {
                title: '验证规则',
                field: 'validatecode',
                align: 'center',
                valign: 'middle',
                width: '150px',
                formatter: function(value, row, index){
                    //console.log("luowen formatter", value, validationDict.value, )
                    return validationDict[value];
                }
            }, {
                title: '是否条件字段',
                field: 'iscondition',
                align: 'center',
                valign: 'middle',
                width: '100px',
                formatter: function (value, row, index) {
                    if (value == 0) {
                        return "否";
                    } else {
                        return "是";
                    }
                }
            }, {
                title: '字段显示顺序',
                field: 'ordersort',
                align: 'center',
                valign: 'middle',
                width: '100px',
            }, {
                title: '字段显示类型',
                field: 'showtype',
                align: 'center',
                valign: 'middle',
                width: '100px',
                sortable: false,
                formatter: function (value, row, index) {
                    var result = "";
                    if (value == 0) {
                        result = "文本框";
                    } else if (value == 1) {
                        result = "下拉框";
                    } else if (value == 2) {
                        result = "单选按钮";
                    } else if (value == 3) {
                        result = "复选框";
                    } else if (value == 4) {
                        result = "日期框";
                    }
                    return result;
                }
            }],
            //onCheck: editField,
            // onUncheck: saveField
        });

        //编辑列
        function editField(row) {
            //查询所有验证规则
            var valiationArray = "";
            $.ajax({
                url: postPath + "/system/sysvalidation/getAllValidation",
                type: "post",
                async: false,
                success: function (data) {
                    valiationArray = data;
                }
            });
            $("#tb_columnfieldList").find("tr").each(function () {
                var trguid = $(this).attr("data-uniqueid");
                if (trguid == row.guid) {
                    var nRow = $(this);
                    var jqTds = $('>td', nRow);
                    var selecttxt = '<select class="form-control input-small" >';
                    if (valiationArray != null) {
                        $.each(valiationArray, function (i, e) {
                            selecttxt += '<option value="' + e.validatecode + '" ' + (row.validatecode == e.validatecode ? "selected='selected'" : "") + '>' + e.validatename + '</option>';
                        })
                    }
                    selecttxt += '</select>';
                    jqTds[4].innerHTML = selecttxt;
                    jqTds[5].innerHTML = '<select class="form-control input-small" style="width:62px !important;">'
                        + '<option ' + (row.iscondition == 0 ? "selected='selected'" : "") + ' value="0">否</option>'
                        + '<option ' + (row.iscondition == 1 ? "selected='selected'" : "") + ' value="1">是</option></select>';
                    jqTds[6].innerHTML = '<input style="width:60px !important;" id="touchspin_1" type="text" value="' + (row.ordersort == null ? "0" : row.ordersort) + '">';
                    jqTds[7].innerHTML = '<select class="form-control input-small" style="width:105px !important;">'
                        + '<option ' + (row.showtype == 0 ? "selected='selected'" : "") + ' value="0">文本框</option>'
                        + '<option ' + (row.showtype == 1 ? "selected='selected'" : "") + ' value="1">下拉列表</option>'
                        + '<option ' + (row.showtype == 2 ? "selected='selected'" : "") + ' value="2">单选按钮</option></select>'
                    //document.getElementById("ordersort").value = row.ordersort;
                    //alert(row.showtype);
                    //document.getElementById("showtype").value = row.showtype;

                }
            });
            $("#touchspin_1").TouchSpin({
                verticalbuttons: true
            });
        }

        //保存列
        function saveField(row) {
            $("#tb_columnfieldList").find("tr").each(function () {
                var trguid = $(this).attr("data-uniqueid");
                if (trguid == row.guid) {
                    var nRow = $(this);
                    var jqTds = $('>td', nRow);
                    var midffvalue = $(':input', nRow);
                    var temp = {
                        guid: row.guid,
                        serviceid: $("#hid_serviceId").val(),
                        validatecode: midffvalue[1].value,
                        iscondition: midffvalue[2].value,
                        ordersort: midffvalue[3].value,
                        showtype: midffvalue[6].value,

                    };
                    $.ajax({
                        type: 'POST',
                        url: postPath + '/system/tableEdit/updateBaseEditByguid',
                        async: false,
                        data: JSON.stringify(temp),
                        dataType: 'json',
                        contentType: "application/json",
                        success: function (data) {
                            $("#tb_columnfieldList").bootstrapTable('refresh');
                        }
                    });
                }
            });
        }

    },
    eventDelBaseEditconfig: function () {//删除列
        $("#btn_columnDel").click(function () {
            var row = $('#tb_columnfieldList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请最少选择一行!");
                return;
            }

            // here is set data list
            var message = " "
            row.forEach(function(e, i){
                message += e.dfname + ", " + e.dfnameCn + "<br/>"
            });

            var deleteFunction = function(result){
                if(result == false)
                    return ""

                var guids = "";
                $.each(row, function (i, e) {
                    if (guids == "") {
                        guids += e.guid;
                    } else {
                        guids += "," + e.guid;
                    }
                });

                $.ajax({
                    url: postPath + "/system/tableEdit/delBaseEditByguid",
                    type: "post",
                    data: {guids: guids},
                    success: function (data) {
                        if (data > 0) {
                            $('#tb_columnfieldList').bootstrapTable('refresh');
                        } else {
                        }
                    }
                });
            };

            confirmDelete( message, deleteFunction);
        });
    }
};

$(function () {
    //参数
    $("#hid_servertype").val(GetQueryString("servertype"));//服务类型 添加使用
    $("#hid_operate").val(GetQueryString("operate")); //操作类型
    $("#hid_serviceId").val(GetQueryString("servercode"));//服务ID  修改使用
    $("#hid_projectid").val(GetQueryString("projectid"));//工程ID 添加修改预留

    tableEditService.prototype.init();
})

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function GetQueryStringSeachTxt(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return r[2];
    return null;
}

function findAllValidationRule(){
    console.log("luowen trigger findAllValidationRule")
    //查询所有验证规则
    $.ajax({
        url: postPath + "/system/sysvalidation/getAllValidation",
        type: "post",
        async: false,
        success: function (validationList) {
            // here is parse value text object
            validationList.forEach(validation => {
                //console.log("validation", validation)
                var value = validation.validatecode;
                var text = validation.validatename ;
                var rule = {
                    value: value,
                    text: text
                }
                validationArray.push(rule);
                validationDict[validation.validatecode]=text;
            });

            console.log("validationArray: ", validationArray)
            console.log("validationDict", validationDict)
        }
    });
}


function setOperateMethod(operateMethod){
    var isAddMode = operateMethod == 'add';
    var addButton = document.getElementById("btn_fieldAdd")
    var updateButton = document.getElementById("btn_fieldUpdate")

    if(isAddMode){
        // add show update hidden
        addButton.style.display = "block";
        updateButton.style.display = "none";

    }else{
        // update show add hidden
        addButton.style.display = "none";
        updateButton.style.display = "block";
    }
    return  isAddMode;
}

function removeFinalChar(content){
    return content = content.substring(0, content.length - 1);
}

function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
